<template>
  <div class="wrap">
    <div class="scroll_class">
      <Tabs ref="tabRef" :config="config" :height="height" @tab="tab" />
      <div v-if="workingList.length > 0" class="filter_insti">
        <scroll-view :scroll-x="true" :show-scrollbar="true" class="scroll_x">
          <div class="scroll_view">
            <div v-for="(i, index) in workingList" :key="index" class="tag">
              <div
                :class="[ i.selected ? (i.isBind === false ? 'inner_tag1' : 'inner_tag') : 'inner_tag2' ]"
                @click="chooseInsti(i.studioId, i.type)"
              >
                {{ i.isBind === false ? `${i.studioName}【已解绑】` : i.studioName }}
              </div>
            </div>
          </div>
        </scroll-view>
        <div class="filter_all" @click="showFilterFn">
          <div class="center_box">
            <div class="icon_filter" />
            筛选
          </div>
        </div>
      </div>
      <scroll-view
        :refresher-enabled="true"
        :refresher-threshold="2"
        :refresher-triggered="updating"
        :scroll-y="true"
        :show-scrollbar="true"
        class="ticket_list"
        @refresherrefresh="innerTab"
        @scrolltolower="scrollTolowerFn"
      >
        <div v-if="ticketList.length > 0" class="inner_ticket">
          <div v-for="(i, index) in ticketList" :key="index" class="ticket_item">
            <up-sticky>
              <div class="head">
                <div class="month_date" @click="showSingleDate">
                  {{ transferDate(currentType === 0 ? i.enterpriseInfo[0].settleTime : i.enterpriseInfo[0].uploadTime) }}
                  <div class="bottom_arrow" />
                </div>
                <div class="total_amount">￥{{ separate(i.totalAmount) }}</div>
              </div>
            </up-sticky>
            <div class="company_content">
              <div v-for="(innerI, innerIndex) in i.enterpriseInfo" :key="innerIndex" class="company_list">
                <div :class="{ inner_list: innerIndex < i.enterpriseInfo.length - 1, inner_list2: innerIndex === i.enterpriseInfo.length - 1 }" @click="goDetail(innerI)">
                  <div class="left">
                    <div class="company_name">{{ currentType === 0 ? innerI.companyName : innerI.enterpriseName }}</div>
                    <div class="time">{{ currentType === 0 ? innerI.settleTime : innerI.uploadTime }}</div>
                  </div>
                  <div class="right">
                    <div class="amount">￥{{ separate(currentType === 0 ? innerI.money : innerI.settlementMoney) }}</div>
                    <div v-if="currentType === 1 && innerI.billStatus" :class="{status0: innerI.billStatus === 3, status1: innerI.billStatus === 1, status2: innerI.billStatus === 2 }">
                      {{ innerI.billStatus === 1 ? '未开票' : innerI.billStatus === 2 ? '已开票' : '部分开票' }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="no_data_time">
          <div class="line_image">
            <Image height="120px" name="no_data_for_time" oss size="240" type="svg" width="400" />
          </div>
          <div class="for_time">没有找到{{ noDataText }}相关记录</div>
          <div class="refresh">请下拉刷新</div>
          <div class="filter_btn" @click="showFilterFn">选择时间</div>
        </div>
      </scroll-view>
    </div>
    <Drawer ref="filterRef" mask>
      <div class="drawer_class">
        <div class="head">
          <div class="space" />
          <div class="title">选择筛选条件</div>
          <div class="right_icon">
            <div class="close_icon" @click="closeDrawer" />
          </div>
        </div>
        <div class="content">
          <div class="time">
            <div class="title">结算时间</div>
            <div class="select">
              <div class="from" @click="showDateDrawer('start')">{{ startDate }}</div>
              <div class="line">
                <div class="inner" />
              </div>
              <div class="to" @click="showDateDrawer('end')">{{ endDate }}</div>
            </div>
          </div>
          <div class="amount">
            <div class="title">金额</div>
            <div class="select">
              <div class="from">
                <up-input
                  v-model="valueLow"
                  border="none"
                  color="#00000073"
                  custom-style="width: 100%;height: 100%;"
                  font-size="14px"
                  input-align="center"
                  placeholder="最低金额"
                  shape="circle"
                />
              </div>
              <div class="line">
                <div class="inner" />
              </div>
              <div class="to">
                <up-input
                  v-model="valueHigh"
                  border="none"
                  color="#00000073"
                  custom-style="width: 100%;height: 100%;"
                  font-size="14px"
                  input-align="center"
                  placeholder="最高金额"
                  shape="circle"
                />
              </div>
            </div>
          </div>
          <div class="status">
            <div class="title">开票状态</div>
            <div class="select">
              <div v-for="(i, index) in statusList" :key="index" class="item">
                <div :class="[ i.active ? 'tag_active' : 'tag' ]" @click="selectStatus(i.name, i.value)">{{ i.name }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="footer">
          <div class="reset" @click="resetFilter">重置</div>
          <div class="confirm" @click="confirm">确定</div>
        </div>
      </div>
    </Drawer>
    <Drawer ref="dateRef" mask>
      <DateSelect :title="dateTitle" @cancel="cancelDate" @value="selectedDate" />
    </Drawer>
    <up-datetime-picker
      v-model="singleDateValue"
      :show="showSingleTime"
      mode="year-month"
      @cancel="cancelSingleDate"
      @confirm="selectedSingleDate"
    />
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { Router, dateToTimestamp, debouncePro } from '@U/common'
import { MsgLoading, PMsgLoadingClean } from '@C/Msg'
import Tabs from '@C/Tabs.vue'
import Drawer from '@C/Drawer.vue'
import DateSelect from '@C/DateSelect.vue'
import Image from '@C/Image.vue'
import { getcurrentStudioList, getcurrentEnterpriseList, getTicketTotalList } from '@P/Ticket/request'

const tabRef: any = ref(null)
const height: any = ref('50px')
const updating: any = ref(false)
const ticketList: any = ref([])
const workingList: any = ref([])
const config: any = ref([
  { label: '其他企业', key: '1' },
  { label: '工作室', key: '0' },
])

const singleDateValue = ref(Date.now())
const params = reactive({
  studioId: Router.route().params?.studioId,
  uploadTime: '',
  enterpriseId: '',
  uploadStartTime: '',
  uploadEndTime: '',
  moneyStart: '',
  moneyEnd: '',
  billStatus: '',
  pageNumber: 1,
  pageSize: 10,
})

const dateTitle: any = ref('')
const currentType: any = ref('')
const currentStudioId: any = ref('')
const currentEnterpriseId: any = ref('')
const separate = (number: any) => number?.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
const chooseInsti = async (studioId: number, type: number) => {
  resetSearch()
  workingList.value.forEach((item: any) => {
    if (item.studioId === studioId) {
      item.selected = true
    } else {
      item.selected = false
    }
  })
  params.studioId = studioId
  currentType.value = type
  await getData(type)
  type === 0
  ? currentStudioId.value = studioId
  : currentEnterpriseId.value = studioId
}
const transferDate = (date: string) => {
  if (!date) return '--'
  const d = date.substring(0, 7)
  const t = d.replace('-', '年')
  return `${t}月`
}

const filterRef: any = ref(null)
const dateRef: any = ref(null)
const showSingleTime: any = ref(false)

const noDataText: any = ref('')

const startDate: any = ref('开始日期')
const endDate: any = ref('结束日期')
const dateType: any = ref('')
const valueLow: any = ref('')
const valueHigh: any = ref('')
const ticketStatus: any = ref('')

const singleDate: any = ref('')

const showFilterFn = () => {
  filterRef.value.change()
}

const showSingleDate = () => {
  console.log('singleDateValue', singleDateValue.value)
  showSingleTime.value = true
}

const closeDrawer = () => {
  filterRef.value.change()
}

const statusList: any = ref([
  { name: '未开票', value: '1', active: false },
  { name: '已开票', value: '2', active: false },
  { name: '部分开票', value: '3', active: false },
])

const selectStatus = (name: string, value: string) => {
  statusList.value.forEach((item: object) => {
    if (item.name === name) {
      item.active = true
    } else {
      item.active = false
    }
  })
  ticketStatus.value = value
}

const resetFilter = () => {
  valueLow.value = ''
  valueHigh.value = ''
  startDate.value = '开始日期'
  endDate.value = '结束日期'

  params.billStatus = ''
  params.uploadTime = ''
  statusList.value.forEach((item: object) => {
    item.active = false
  })
}
const confirm = debouncePro(() => innerFn(), 250)

const innerFn = () => {
  resetSearch()
  filterRef.value.change()
  params.uploadTime = ''
  params.uploadStartTime = startDate.value !== '开始日期' ? startDate.value : ''
  params.uploadEndTime = endDate.value !== '结束日期' ? endDate.value : ''

  noDataText.value = `${startDate.value !== '开始日期' ? startDate.value : ''}至${endDate.value !== '结束日期' ? endDate.value : ''}`

  params.billStatus = ticketStatus.value || ''
  params.moneyStart = valueLow.value || ''
  params.moneyEnd = valueHigh.value || ''
  getData(currentType.value)
}

const showDateDrawer = (type: string) => {
  if (type === 'start') dateTitle.value = '请选择开始日期'
  else if (type === 'end') dateTitle.value = '请选择结束日期'

  if (type === 'end' && startDate.value === '开始日期') {
    uni.showToast({ title: '请选择开始日期', duration: 2000, icon: 'none' })
    return
  }
  dateType.value = type
  dateRef.value.change()
}

const selectedDate = debouncePro((date: string, dateAll: string) => innerDateFn(date, dateAll), 250)

const innerDateFn = (date: string, dateAll: string) => {
  console.log('当前选中日期为：', date, dateAll)
  const timestamp = dateToTimestamp(date)
  if (dateType.value === 'end' && timestamp < dateToTimestamp(startDate.value)) {
    uni.showToast({ title: '结束日期应大于开始日期', duration: 2000, icon: 'none' })
    return
  }
  dateType.value === 'start' ? startDate.value = date : endDate.value = date
  dateRef.value.change()
}

const cancelDate = () => {
  dateRef.value.change()
}

const selectedSingleDate = debouncePro((date: string) => innerSingleDateFn(date), 250)

const innerSingleDateFn = (date: string) => {
  singleDate.value = timestampToYearMonth(date['value' as any])
  noDataText.value = singleDate.value
  params.uploadTime = singleDate.value
  getData(currentType.value)
  showSingleTime.value = false
}

// 时间戳转 年月
const timestampToYearMonth = (timestamp: string | number) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  let month: any = date.getMonth() + 1
  month = (month < 10 ? `0${month}` : month)
  return `${year}-${month}`
}

const cancelSingleDate = () => {
  showSingleTime.value = false
}

const goDetail = (info: any) => {
  Router.push('gl_ticket_detail', { info, type: currentType.value })
}

async function getData(type: number) {
  await MsgLoading()
  const api = (type === 0 ? getcurrentStudioList : getcurrentEnterpriseList)
  const res = await api(params).finally(() => {})
  if (res?.code === 200) {
    PMsgLoadingClean()
    res?.data.forEach((item: any) => {
      const obj: any = {
        enterpriseInfo: [],
        month: item.month,
        totalAmount: '',
        total: 0,
        pages: 1,
      }
      let totalMoney: any = 0
      item.enterpriseInfo.rows.forEach((innerItem: any) => {
        let innerObj: any = {}
        innerObj = innerItem as any
        totalMoney += (type === 0 ? innerItem.money : innerItem.settlementMoney)
        obj.enterpriseInfo.push(innerObj)
      })
      obj.totalAmount = totalMoney as any
      obj.total = item.enterpriseInfo.total
      obj.pages = item.enterpriseInfo.pages
      ticketList.value.push(obj)
    })
  }
  setTimeout(() => {
    updating.value = false
  }, 1000)
}

async function getTagData(type: any) {
  const res = await getTicketTotalList().finally(() => {})
  if (res.code === 200 && res.data) {
    workingList.value = []
    res.data.forEach((item: any) => {
      if (type === item.type) {
        const obj = {
          studioName: item.name,
          studioId: item.id,
          type: item.type,
          selected: false,
          isBind: item.isBind,
        }
        item.id === (type === 0 ? currentStudioId.value : currentEnterpriseId.value)
        ? (workingList.value.unshift(obj) && (obj.selected = true))
        : workingList.value.push(obj)
      }
    })
  }
}

const resetSearch = () => {
  ticketList.value = []
  Object.keys(params).forEach((item: string) => {
    item !== 'studioId' ? ((params as any)[item] = '') : ''
  })
  params.pageNumber = 1
  params.pageSize = 10
}

const innerTab = async () => {
  resetSearch()
  noDataText.value = ''
  updating.value = true
  await getTagData(currentType.value)
  workingList.value.length > 0
  ? await chooseInsti(workingList.value[0].studioId, currentType.value)
  : ((ticketList.value = []))
  updating.value = false
}
const tab = async (v: any) => {
  currentType.value = parseInt(v)
  updating.value = true
}
const scrollTolowerFn = () => {
  if (params.pageNumber > ticketList.value[0].pages || ticketList.value.enterpriseInfo?.length >= ticketList.value.total) return
  params.pageNumber += 1
  getData(currentType.value)
}
onMounted(async () => {
  currentType.value = Router.route().params?.type
  currentType.value === 0 ? (currentStudioId.value = Router.route().params?.studioId) : (currentEnterpriseId.value = Router.route().params?.studioId)
  tabRef.value.change(currentType.value.toString())
  updating.value = true
})

</script>
<style lang="less" scoped>
.wrap {
  width: 100%;
  height: 100%;
  background-color: #F2F2F7;
  .scroll_class {
    width: 100%;
    height: 100%;
    .filter_insti {
      width: 100%;
      height: 114rpx;
      background-color: #fff;
      border-top: 2rpx solid rgba(0, 0, 0, .1);
      display: flex;
      align-items: center;
      .scroll_x {
        width: calc(100vw - 140rpx);
        height: 100%;
        .scroll_view {
          width: max-content;
          height: 100%;
          display: flex;
          align-items: center;
          padding-left: 24rpx;
          .tag {
            min-width: 200rpx;
            height: 60rpx;
            margin-right: 24rpx;
            display: flex;
            .inner_tag, .inner_tag1, .inner_tag2 {
              min-width: 200rpx;
              height: 100%;
              display: flex;
              line-height: 60rpx;
              border-radius: 30rpx;
              box-sizing: border-box;
              padding: 0 16rpx;
              text-align: center;
              // white-space: nowrap;
              // overflow: hidden;
              // text-overflow: ellipsis;
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 28rpx;
            }
            .inner_tag {
              background: #1890FF;
              color: #FFFFFF;
            }
            .inner_tag1 {
              background: #B9BBB9;
              color: #FFFFFF;
            }
            .inner_tag2 {
              border: 2rpx solid #8C8C8C;
              color: rgba(0,0,0,0.45);
            }
          }
        }
      }
      .filter_all {
        width: 140rpx;
        height: 100%;
        box-shadow: -8rpx 0 4rpx -4rpx rgba(0, 0, 0, 0.1);
        .center_box {
          width: 96rpx;
          height: 100%;
          margin: 0 auto;
          display: flex;
          align-items: center;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 32rpx;
          color: rgba(0,0,0,0.65);
          .icon_filter {
            width: 24rpx;
            height: 26rpx;
            margin-right: 8rpx;
            background: url('https://shoudaostatic.oss-cn-shanghai.aliyuncs.com/MEIDAO-ZHIKE/filter.svg');
            background-size: cover;
          }
        }
      }
    }
    .no_data {
      width: 100%;
      height: 300rpx;
      margin-top: 200rpx;
      display: flex;
      align-items: center;
      justify-content: space-around;
    }
    .ticket_list {
      width: 100%;
      height: calc(100vh - 214rpx);
      .inner_ticket {
        width: 100%;
        height: auto;
        .ticket_item {
          width: 100%;
          min-height: 256rpx;
          .head {
            width: 100%;
            height: 100rpx;
            padding: 0 24rpx;
            display: flex;
            justify-content: space-between;
            background-color: #F2F2F7;
            z-index: 1000;
            .month_date, .total_amount {
              height: 100rpx;
              line-height: 100rpx;
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 32rpx;
            }
            .month_date {
              width: 40%;
              color: rgba(0,0,0,0.65);
              display: flex;
              align-items: center;
              .bottom_arrow {
                width: 26rpx;
                height: 26rpx;
                background: url('https://shoudaostatic.oss-cn-shanghai.aliyuncs.com/MEIDAO-ZHIKE/bottom.svg');
                background-size: cover;
              }
            }
            .total_amount {
              width: 60%;
              text-align: right;
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 32rpx;
              color: rgba(0,0,0,0.65);
            }
          }
          .company_content {
            width: 100%;
            background-color: #fff;
            .company_list, .company_list2 {
              width: 100%;
              height: 154rpx;
              display: flex;
              align-items: center;
              padding: 0 48rpx;
              .inner_list, .inner_list2 {
                width: 100%;
                height: 100%;
                margin: 0 auto;
                padding: 24rpx 0;
                display: flex;
                .left, .right {
                  height: 100%;
                  display: flex;
                  flex-direction: column;
                  justify-content: space-around;
                }
                .left {
                  width: 65%;
                  .company_name {
                    width: 100%;
                    height: 40%;
                    font-family: PingFangSC, PingFang SC;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    font-weight: 400;
                    font-size: 28rpx;
                    color: #595959;
                  }
                  .time {
                    width: 100%;
                    height: 40%;
                    font-family: PingFangSC, PingFang SC;
                    font-weight: 400;
                    font-size: 24rpx;
                    color: rgba(0,0,0,0.45);
                  }
                }
                .right {
                  width: 35%;
                  .amount {
                    width: 100%;
                    height: 40%;
                    font-family: PingFangSC, PingFang SC;
                    font-weight: 400;
                    font-size: 28rpx;
                    color: #595959;
                    text-align: right;
                  }
                  .status0, .status1, .status2 {
                    width: 100%;
                    height: 40%;
                    font-family: PingFangSC, PingFang SC;
                    font-weight: 400;
                    font-size: 24rpx;
                    color: rgba(0,0,0,0.45);
                    text-align: right;
                  }
                  .status0 {
                    color: #1890ff;
                  }
                  .status1 {
                    color: rgba(0,0,0,0.45);
                  }
                  .status2 {
                    color: #2DC76D;
                  }
                }
              }
              .inner_list {
                border-bottom: 2rpx solid rgba(0,0,0,0.1);
              }
            }
          }
        }
      }
      .no_data_time {
        width: 100%;
        height: 800rpx;
        margin-top: 0;
        padding-top: 100rpx;
        .line_image {
          width: 100%;
          display: flex;
          justify-content: space-around;
        }
        .for_time {
          width: 100%;
          height: 60rpx;
          line-height: 60rpx;
          text-align: center;
          margin-top: 24rpx;
        }
        .refresh {
          width: 100%;
          height: 40rpx;
          line-height: 40rpx;
          text-align: center;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 28rpx;
          color: #8C8C8C;
          margin-top: 24rpx;
        }
        .filter_btn {
          width: 180rpx;
          height: 60rpx;
          margin: 0 auto;
          margin-top: 24rpx;
          line-height: 56rpx;
          border-radius: 36rpx;
          border: 2rpx solid #1890FF;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 28rpx;
          color: #1890FF;
          text-align: center;
        }
      }
    }
  }
  .drawer_class {
    width: 100%;
    height: 846rpx;
    background-color: #fff;
    border-radius: 28rpx;
    backdrop-filter: blur(0px);
    .head {
      width: 100%;
      height: 120rpx;
      display: flex;
      justify-content: space-around;
      .space {
        width: 33%;
        height: 100%;
      }
      .title {
        width: 33%;
        height: 100%;
        line-height: 120rpx;
        text-align: center;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 32rpx;
        color: rgba(0,0,0,0.85);
      }
      .right_icon {
        width: 33.3%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        .close_icon {
          width: 44rpx;
          height: 44rpx;
          margin-right: 30rpx;
          background: url('https://shoudaostatic.oss-cn-shanghai.aliyuncs.com/MEIDAO-ZHIKE/close.png');
          background-size: cover;
        }
      }
    }
    .content {
      width: 100%;
      height: 526rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .time, .amount, .status {
        width: 89%;
        height: 128rpx;
        margin: 0 auto;
        .title {
          width: 100%;
          height: 50%;
          font-family: PingFangSC, PingFang SC;
          font-weight: 500;
          font-size: 30rpx;
          color: rgba(0,0,0,0.65);
        }
        .select {
          width: 100%;
          height: 50%;
          display: flex;
          .line {
            width: 7.4%;
            height: 100%;
            display: flex;
            align-items: center;
            .inner {
              width: 50%;
              height: 2rpx;
              margin: 0 auto;
              background: #CBCCCD;
            }
          }
          .from, .to {
            width: 46%;
            height: 70rpx;
            line-height: 70rpx;
            border-radius: 34rpx;
            text-align: center;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 28rpx;
            color: rgba(0,0,0,0.45);
            background: #F5F6F7;
            .u-input {
              width: 100%;
              height: 100%;
              line-height: 70rpx;
              text-align: center;
            }
          }
          .item {
            width: 26.6%;
            height: 100%;
            margin-right: 3.7%;
            .tag_active, .tag {
              width: 100%;
              height: 100%;
              border-radius: 36rpx;
              line-height: 64rpx;
              text-align: center;
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 28rpx;
            }
            .tag_active {
              background: #2094FF;
              color: #fff;
            }
            .tag {
              background: #F5F6F7;
              color: rgba(0,0,0,0.45);
            }
          }
        }
      }
    }
    .footer {
      width: 89%;
      height: 200rpx;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .reset, .confirm {
        width: 47.7%;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        border-radius: 40rpx;
        box-sizing: border-box;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 36rpx;
      }
      .reset {
        border: 2rpx solid #1890FF;
        color: #1890FF;
      }
      .confirm {
        background-color: #1890FF;
        color: #fff;
      }
    }
  }
  .drawerClassDate {
    width: 100%;
    height: 646rpx;
    background-color: #fff;
    border-radius: 28rpx;
    backdrop-filter: blur(0rpx);
  }
}
</style>
